package com.zz.framework.core.ext

import android.content.ClipData
import android.net.Uri
import android.text.TextUtils
import com.github.promeg.pinyinhelper.Pinyin
import com.zz.framework.core.BaseApp
import com.zz.framework.core.utils.language.LanguageManager
import java.math.BigDecimal
import java.net.URLEncoder
import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets
import java.util.Locale
import java.util.regex.Matcher
import java.util.regex.Pattern
import kotlin.experimental.and


/**
 * Copyright © 2024 zhun All rights reserved.
 * Created by Zha0Zhun on 2024/6/30 10:41.
 * @author: Zha0Zhun 1820022519@qq.com
 * @version: V1.0
 */
/**
 * 字符串转Url编码
 * @receiver String?
 * @return String
 */
fun String?.toEncodedUrl(): String = URLEncoder.encode(if (TextUtils.isEmpty(this)) " " else this, StandardCharsets.UTF_8.toString())

//编码
fun String?.toUriEncode(): String = Uri.encode(if (TextUtils.isEmpty(this)) " " else this, StandardCharsets.UTF_8.toString())

//解码
fun String?.toUriDecode(): String = Uri.decode(if (TextUtils.isEmpty(this)) " " else this)

/**
 * 字符串转Long
 * @receiver String?
 * @return Long
 */
fun String?.getLong(): Long {
    if (this == null || "" == this.trim { it <= ' ' }) {
        return 0L
    }
    return try {
        java.lang.Long.parseLong(this.trim { it <= ' ' })
    } catch (e: Exception) {
        0L
    }
}

/**
 * 字符串转Float
 * @receiver String?
 * @return Float
 */
fun String?.getFloat(): Float {
    if (this == null || "" == this.trim { it <= ' ' }) {
        return 0f
    }
    return try {
        this.trim { it <= ' ' }.toFloat()
    } catch (e: Exception) {
        0f
    }
}

/**
 * 字符串转Double
 * @receiver String?
 * @return Double
 */
fun String?.getDouble(): Double {
    if (this == null || "" == this.trim { it <= ' ' }) {
        return 0.0
    }
    return try {
        this.trim { it <= ' ' }.toDouble()
    } catch (e: Exception) {
        0.0
    }
}

fun String?.getBigDecimal(): BigDecimal {
    if (this == null || "" == this.trim { it <= ' ' }) {
        return BigDecimal.ZERO
    }
    return BigDecimal(this.trim { it <= ' ' })
}

/**
 * 字符串转Int
 * @receiver String?
 * @return Int
 */
fun String?.getInt(): Int {
    if (this == null || "" == this.trim { it <= ' ' }) {
        return 0
    }
    return try {
        Integer.parseInt(this.trim { it <= ' ' })
    } catch (e: Exception) {
        0
    }
}

/**
 * 驼峰转下划线
 * @receiver String?
 * @return String
 */
fun String?.camelToUnderline(): String {
    if (this == null || "" == this.trim { it <= ' ' }) {
        return ""
    }
    val len = this.length
    val sb = StringBuilder(len)
    for (i in 0 until len) {
        val c = this.get(i)
        if (Character.isUpperCase(c)) {
            sb.append("_")
            sb.append(Character.toLowerCase(c))
        } else {
            sb.append(c)
        }
    }
    return sb.toString()
}


/**
 * if [String.isNullOrEmpty], invoke f() otherwise invoke t()
 * @receiver String?
 * @param f Function0<T>
 * @param t Function0<T>
 * @return T
 */
fun <T> String?.notNull(f: () -> T, t: () -> T): T {
    return if (isNullOrEmpty()) f() else t()
}

/**
 * whether string only contains digits
 */
fun String.areDigitsOnly() = matches(Regex("[0-9]+"))


/**
 * 是否是手机号
 */
fun String.isPhone() = "^[1][0-9]{10}$".toRegex().matches(this)

/**
 * 是否是邮箱地址
 */
//fun String.isEmail() = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?".toRegex().matches(this)
/**
 * 正则表达式 判断邮箱格式是否正确
 */
fun String?.isEmail(): Boolean {
    if (this.isNullOrEmpty()) return false
    val str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"
    val p: Pattern = Pattern.compile(str)
    val m: Matcher = p.matcher(this)
    return m.matches()
}

/**
 * 是否是身份证号码
 */
fun String.isIDCard() = "[1-9]\\d{16}[a-zA-Z0-9]".toRegex().matches(this)

/**
 * 是否是中文字符
 */
fun String.isChinese() = "^[\u4E00-\u9FA5]+$".toRegex().matches(this)


fun String.substring(startStr: String = "", endStr: String = ""): String {
    val start = if (startStr.isEmpty()) {
        0
    } else {
        this.indexOf(startStr) + startStr.length
    }
    val end = if (endStr.isEmpty()) {
        this.length
    } else {
        this.indexOf(endStr)
    }
    return this.substring(start, end)
}


//数字转中文
fun Int.toChinese(): String {
    return "${this}".toChinese()
}

fun String?.toChinese(): String {
    if (this == null || "" == this.trim { it <= ' ' }) {
        return ""
    }
    val sb = StringBuilder()
    for (element in this) {
        if (element in '0'..'9') {
            sb.append("零一二三四五六七八九"[element - '0'])
        } else {
            sb.append(element)
        }
    }
    return sb.toString()
}

fun ByteArray.toHexString(withPrefix: Boolean = true): String {
    val stringBuilder = StringBuilder()
    if (withPrefix) {
        stringBuilder.append("0x")
    }
    for (element in this) {
        stringBuilder.append(String.format("%02x", element and 0xFF.toByte()))
    }
    return stringBuilder.toString()
}


fun String.hexStringToByteArray(): ByteArray {
    val HEX_CHARS = "0123456789ABCDEF"
    val result = ByteArray(length / 2)
    for (i in indices step 2) {
        val firstIndex = HEX_CHARS.indexOf(this[i].toUpperCase());
        val secondIndex = HEX_CHARS.indexOf(this[i + 1].toUpperCase());
        val octet = firstIndex.shl(4).or(secondIndex)
        result.set(i.shr(1), octet.toByte())
    }
    return result
}

//移除字符串最后一个空格
fun String?.removeLastSpace(): String {
    if (this == null || "" == this.trim { it <= ' ' }) {
        return ""
    }
    if (this.getLastChar() != " ") {
        return this
    }
    return this.substring(0, this.length - 1)
}

//获取字符串最后一个字符
fun String?.getLastChar(): String {
    if (this == null || "" == this.trim { it <= ' ' }) {
        return ""
    }
    return this.substring(this.length - 1, this.length)
}


fun String.copy() {
    val clipData = ClipData.newPlainText(
        null,
        this
    )
    BaseApp.context.clipboardManager?.setPrimaryClip(clipData)
}


fun ByteBuffer?.toUtf8String(): String {
     if (this != null) {
         return StandardCharsets.UTF_8.decode(this).toString()
    } else {
         return ""
    }
}

fun String?.toByteBuffer(): ByteBuffer {
    // 创建一个 ByteBuffer 并存储字符串的字节数据
    return if (this != null) {
        ByteBuffer.wrap(this.toByteArray(StandardCharsets.UTF_8))
    } else {
        ByteBuffer.wrap("".toByteArray(StandardCharsets.UTF_8))
    }
}




/**
 * 中文转大写拼音
 * @receiver String
 * @param separator String
 * @return String
 */
fun String.toPinyinUpperCase(separator:String= ""):String{
    return Pinyin.toPinyin(this,separator).uppercase()
}

/**
 * 中文转小写拼音
 * @receiver String
 * @param separator String
 * @return String
 */
fun String.toPinyinLowerCase(separator:String= ""):String{
    return Pinyin.toPinyin(this,separator).lowercase()
}

/**
 * 中文转驼峰拼音
 * @receiver String
 * @return String
 */
fun String.toPinyinCamelCase(): String {
    return toPinyinLowerCase(",").split(",").joinToString(separator = "") {
        it.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.ROOT) else it.toString() }
    }
}


fun String.getLangKey():String {
    //去除所有标点
    val pinyin = toPinyinLowerCase().replace("[^a-zA-Z0-9\\u4e00-\\u9fa5]".toRegex(), "")
    return pinyin.take(50)
}


fun String.toLanguage() = LanguageManager.getString(this)
fun String.toLanguage_() = LanguageManager.getString_(this)
fun Int.toLanguage() = LanguageManager.getString(this)
fun Int.toLanguage_() = LanguageManager.getString_(this)
fun Int.toLanguage(vararg formatArgs: Any?) = LanguageManager.getString(this,formatArgs)
